const { bfmetaSDK } = require('../../../util/util')
const { signature } = require('../../../util/signature')

const trBeExchangeAny = () => {
    return async (req, res, next) => {
        try {
            let data = {
                transactionSignature: req.body.transactionSignature,
                toExchangeAssetPrealnum: req.body.toExchangeAssetPrealnum,
                beExchangeAssetPrealnum: req.body.beExchangeAssetPrealnum,
                exchangeAny: {
                    toExchangeSource:req.body.toExchangeSource,
                    toExchangeChainName: req.body.toExchangeChainName,
                    beExchangeSource:req.body.beExchangeSource,
                    beExchangeChainName: req.body.beExchangeChainName,
                    cipherPublicKeys: [], // string[]
                    toExchangeParentAssetType: req.body.toExchangeParentAssetType, //number
                    beExchangeParentAssetType: req.body.beExchangeParentAssetType, //number
                    toExchangeAssetType: req.body.toExchangeAssetType,
                    beExchangeAssetType: req.body.beExchangeAssetType,
                    toExchangeAssetPrealnum: req.body.toExchangeAssetPrealnum,
                    beExchangeAssetPrealnum: req.body.beExchangeAssetPrealnum,
                },
                recipientId: req.body.recipientId,
                taxInformation: {
                    taxCollector: req.body.taxCollector,
                    taxAssetPrealnum: req.body.taxAssetPrealnum,
                },
                publicKey: req.body.publicKey,
                fee: "2000",
                applyBlockHeight: 1
            }
            // 创建接受任意资产交换事件
            let result = await bfmetaSDK.api.transaction.createBeExchangeAny(data)
            if(!result.success){
                return res.status(400).send(result)
            }
            // 对该事件签名
            const _signature = await signature(result.result.buffer, req.body.secretKey)
            data = {
                signature: _signature,
                buffer: result.result.buffer
            }
            // 广播创建接受任意资产交换事件
            result = await bfmetaSDK.api.transaction.broadcastBeExchangeAny(data)
            if(!result.success){
                return res.status(400).send(result)
            }
            res.status(200).send(result)
        } catch (error) {
            next(error)
        }
    }
}

module.exports = { trBeExchangeAny }